
import Common from '../../../public/actions/employing/common';
import ProcessTemplate from './processTmp';
import {getQueryCondition} from '../../../../hrpub/common/utils/utils';

import FormEdit from '../components/AddPage/actions/formEdit';

export default class BatchAddAction extends Common {

    constructor(comp) {
        super();
        this.comp = comp;
    }

    extend = [ProcessTemplate, FormEdit]

    historyState = null;

    // 打开批量新增的查询台窗
    openBatchAddSearchModal = () => {
        const {props} = this.comp;
        const {search, meta} = props;
        let template = meta.getMeta();

        this.addQueryConditionToMultiAddSearch(template, 'batchaddmultiadd', 4);

        search.openAdvSearch('batchaddmultiadd', true);
    }

    // 初始化弹窗
    initBatchModal = async () => {
        const {
            props: {
                dispatch,
                emp
            }
        } = this.comp;

        let postData = {
            pk_org: emp.orgValue.refpk,
            transType: emp.leaveType.refpk
        };
        
        let res = await dispatch({
            type: 'emp/initBatchAddModal',
            payload: {
                postData: postData
            }
        });

        if(res.success) {
            return true;
        }
    }

    // 打开批量新增弹窗
    openBatchModal = async () => {
        const {
            props: {
                dispatch,
                emp
            }
        } = this.comp;

        if(!emp.leaveType) {
            this.toast({
                color: 'danger',
                content: emp.language['gx6008-000081'] // 当前选择的离职业务类型为空，不能进行后续操作
            });
            return;
        }
        let initRes = await this.initBatchModal();
 
        if(initRes) {
            this.update({
                batchAddModalVisible: true
            });
        }
    }

    // 关闭批量新增弹窗
    closeBatchModal = () => {
        const {
            props: {
                meta,
                emp,
                editTable
            }
        } = this.comp;
        editTable.setTableData('batchaddlist', {rows: []})
        let template = meta.getMeta();
        template.pageid = emp.pageid;
        meta.setMeta(template)

        this.update({
            batchAddModalVisible: false,
            batchAddCurrentStep: 0
        });
    }

    // 为了解决查询不能是async的问题
    toSearchWrapper = () => {
        this.toSearch();
    }

    // 批量新增弹窗第一步条件选择查询弹窗点击确认
    toSearch = async () => {
        const {props} = this.comp;
        const {dispatch, emp, editTable, search, meta} = props;

        let template = meta.getMeta();
        let postData = {
            ...getQueryCondition(props, 'batchaddmultiadd'),
            listpks: this.getExistPks(),
            oid: template['batchaddmultiadd'].oid,
            pk_org: emp.orgValue.refpk
        };

        try {
            let res = await dispatch({
                type: 'emp/getBatchAddTableDataBySearch',
                payload: {
                    postData: postData
                }
            });
            if(res.success && res.data && res.data.list) {
                this.addonRowToTable(res.data.list.list.rows);
            }
        }
        catch(e) {
            console.error(`toSearch: ${e}`);
        }
    }

    // 获取已存在的listpks
    getExistPks = () => {
        const {props} = this.comp;
        const {dispatch, emp, editTable} = props;

        let tableData = editTable.getAllRows('batchaddlist');

        let listpks = tableData.map((item) => {
            return item.values['pk_psnjob'].value;
        });

        return listpks.join(',')
    }

    // 批量新增弹窗第一步参照选择逻辑
    changePersonRefer = async (value) => {
        const {props} = this.comp;
        const {dispatch, emp, editTable} = props;

        let postData = {
            listpks: this.getExistPks(),
            pk_org: emp.orgValue.refpk,
            refpks: ''
        };

        let refpks = value.map((item) => {
            return item.refpk;
        });
        postData['refpks'] = refpks.join(',');

        try {
            let res = await dispatch({
                type: 'emp/getBatchAddTableDataByRefer',
                payload: {
                    postData: postData
                }
            });

            if(res.data && res.data.confirmMsg) {
                this.toast({
                    color: 'danger',
                    content: res.data.confirmMsg
                });
            }

            if(res.success && res.data && res.data.list) {
                this.addonRowToTable(res.data.list.list.rows);
            }
        }
        catch(e) {
            console.error(`changePersonRefer: ${e}`);
        }
    }

    // 在表格后面追加行
    addonRowToTable = (rows) => {
        const {props} = this.comp;
        const {editTable} = props;

        let dataList = editTable.getAllRows('batchaddlist');
        dataList = dataList.concat(rows);
        editTable.setTableData('batchaddlist', {rows: dataList}, false);
        this.comp.setState({
            selectAll: false
        });
    }

    // 获取并存储选择的行
    getSelectedRows = () => {
        const {props, state} = this.comp;
        const {emp, dispatch, editTable} = props;

        let selectedRows = [];

        if(state.selectAll) {
            selectedRows = editTable.getAllRows('batchaddlist');
        }
        else {
            selectedRows = editTable.getCheckedRows('batchaddlist').map((item) => {
                return item.data
            });
        }

        this.comp.setState({
            selectRows: this.deepCopy(selectedRows)
        });

        return selectedRows;
    }

    // 批量添加弹窗点击下一步
    goToNextStep = async () => {
        const {props, action} = this.comp;
        const {emp, dispatch, editTable, form, meta} = props;

        let template = meta.getMeta();

        this.historyState = this.deepCopy(editTable.getAllRows('batchaddlist'));

        let postData = {
            pk_org: emp.orgValue.refpk,
            transType: emp.leaveType.refpk
        };
        
        let selectRows = this.getSelectedRows();

        if(selectRows && selectRows.length <= 0) {
            this.toast({
                color: 'warning',
                content: emp.language['gx6008-000288'] || '请选择要离职的人员' //'请选择要离职的人员!'
            });
        }
        else {
            try {
                let res = await dispatch({
                    type: 'emp/batchAddNextStep',
                    payload: {
                        postData: postData
                    }
                });
                let {formData, ...other} = res.data;
                Object.assign(template, other);
                template.pageid = emp.batchAddPageId;

                // template['formrelation']['batchaddcard'] = [];
                // template['formrelation']['card'].map((item) => {
                //     let name = `batch${item}`;
                //     template[name] = {
                //         ...res.data.template[item],
                //         code: name,
                //         relationcode: name
                //     }
                //     template['formrelation']['batchaddcard'].push(name);
                // });
                // template['list'] = res.data.template['list'];
                // template['batchaddcard'] = this.deepCopy(res.data.template['card']);
                // action.pAct.processTemplate(template)
                meta.setMeta(template, () => {
                    this.update({
                        batchAddCurrentStep: 1
                    });
                    form.setFormStatus('card_batch', 'edit');
                    setTimeout(() => {
                        form.setAllFormValue({
                            // batchaddcard: res.data.defaultValue.head.card
                            'card_batch': formData['card_batch']
                        }); 
                    }, 10);
                   
                    // 延迟避免跟上面设置状态冲突
                    setTimeout(() => {
                        template['formrelation']['card_batch'].map((item) => {
                            form.openArea('card_batch',item);
                        });
                    }, 1);
                });
            }
            catch(e) {
                console.error(e);
            }
        }
    }

    // 批量添加弹窗点击上一步
    goToPrevStep = () => {
        const {props} = this.comp;
        const {emp, dispatch, editTable} = props;

        this.update({
            batchAddCurrentStep: 0
        });

        if(this.historyState) {
            editTable.setTableData('batchaddlist', {rows: this.historyState}, false);
            this.historyState = null;
        }
    }

    // 当表格选择全部的时候
    selectedAll = (...args) => {
        this.comp.setState({
            selectAll: args[2]
        });
    }

    // 批量新增弹窗点击完成
    submitBatchAdd = async () => {
        const {props, state} = this.comp;
        const {emp, dispatch, meta, form} = props;

        if(!form.isCheckNow('card_batch')) {
            return;
        }

        let postData = {
            listpks: '',
            model: form.getAllFormValue('card_batch'),
            pk_org: emp.orgValue.refpk
        };

        let listpks = state.selectRows.map((item) => {
            return item.values['pk_psnjob'].value
        });

        postData['listpks'] = listpks.join(',');

        try {
            let res = await dispatch({
                type: 'emp/batchAddModalSubmitChecked',
                payload: {
                    postData: postData
                }
            });

            if(res.data.warningMsg) {
                this.toast({
                    color: 'warning',
                    content: res.data.warningMsg
                });
                //return;
            }
        }
        catch(e) {
            console.error(e);
            return false;
        }
        
        postData['transType'] = emp.leaveType.refpk;

        try {
            let res = await dispatch({
                type: 'emp/batchAddModalSubmit',
                payload: {
                    postData: postData
                }
            });

            if(res.success) {
                this.toast({
                    color: 'success',
                    content: emp.language['gx6008-000066'] // 新增成功
                });
                this.closeBatchModal();
                this.pubSub.publish('getMainTableData');
            }
        }
        catch(e) {
        }
    }
}